<template>
  <div class="doctor-form-container">
    <el-card class="form-card">
      <h2>医生信息录入</h2>

      <el-form :model="form" label-width="120px" label-position="left">
        <!-- 医生姓名 -->
        <el-form-item label="医生姓名:" required>
          <el-input v-model="form.name" placeholder="请输入医生姓名" clearable />
        </el-form-item>

        <!-- 医生头像 -->
        <el-form-item label="医生头像:">
          <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleAvatarChange"
          >
            <img v-if="form.avatar" :src="form.avatar" class="avatar"  alt="avatar"/>
            <el-icon v-else class="avatar-uploader-icon"><UserFilled /></el-icon>
            <div class="upload-tip">
              <el-button type="primary" text>上传头像</el-button>
              <span class="tip-text">支持格式: jpg、png、jpeg</span>
              <span v-if="uploading" class="uploading-text">上传中...</span>
            </div>
          </el-upload>
        </el-form-item>

        <!-- 医生职称 -->
        <el-form-item label="医生职称:">
          <el-select v-model="form.title" placeholder="请选择职称">
            <el-option
                v-for="item in titleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

<!--        &lt;!&ndash; 所属医院 &ndash;&gt;-->
<!--        <el-form-item label="所属医院:">-->
<!--          <el-select v-model="form.hospitalId" placeholder="请选择医院">-->
<!--            <el-option-->
<!--                v-for="hospital in hospitalOptions"-->
<!--                :key="hospital.value"-->
<!--                :label="hospital.label"-->
<!--                :value="hospital.value"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->

<!--        &lt;!&ndash; 所属科室 &ndash;&gt;-->
<!--        <el-form-item label="所属科室:">-->
<!--          <el-cascader-->
<!--              v-model="form.departmentPath"-->
<!--              :options="departmentOptions"-->
<!--              :props="{ expandTrigger: 'hover' }"-->
<!--              clearable-->
<!--          />-->
<!--        </el-form-item>-->

<!--        &lt;!&ndash; 挂号费用 &ndash;&gt;-->
<!--        <el-form-item label="挂号费用:">-->
<!--          <el-input-number-->
<!--              v-model="form.registrationFee"-->
<!--              :min="0"-->
<!--              :precision="2"-->
<!--              :controls-position="'right'"-->
<!--          >-->
<!--            <template #prefix>￥</template>-->
<!--          </el-input-number>-->
<!--        </el-form-item>-->

        <!-- 问诊收费 -->
        <el-form-item label="问诊收费:">
          <div class="consultation-fee">
            <el-checkbox v-model="form.enableTextConsultation" label="图文" />
            <el-input-number
                v-model="form.consultationFeeText"
                :min="0"
                :precision="2"
                :disabled="!form.enableTextConsultation"
            >
              <template #suffix>元/次</template>
            </el-input-number>

            <el-checkbox v-model="form.enablePhoneConsultation" label="电话" class="phone-consultation" />
            <el-input-number
                v-model="form.consultationFeePhone"
                :min="0"
                :precision="2"
                :disabled="!form.enablePhoneConsultation"
            >
              <template #suffix>元/15分钟</template>
            </el-input-number>
          </div>
        </el-form-item>

        <!-- 擅长领域 -->
        <el-form-item label="擅长领域:">
          <el-input
              v-model="form.expertise"
              type="textarea"
              :rows="4"
              placeholder="请描述医生的擅长领域，擅长治疗的疾病"
              maxlength="500"
              show-word-limit
          />
        </el-form-item>

        <!-- 医生简介 -->
        <el-form-item label="医生简介:">
          <el-input
              v-model="form.description"
              type="textarea"
              :rows="4"
              placeholder="请描述医生的介绍信息"
              maxlength="1000"
              show-word-limit
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import { UserFilled } from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";
import {router} from "@/router/index.js";
import axios from "axios";

// 表单数据
const form = ref({})

// 职称选项
const titleOptions = ref([])
const getTitleOptions = () => {
  axios.get('/doctor/getTitle')
      .then(res => {
        console.log('API响应:', res.data) // 查看实际返回的数据结构

        // 确保数据格式正确
        if (res.data && res.data.obj) {
          titleOptions.value = res.data.obj.map(item => ({
            value: item.value || item.id || item, // 确保有value
            label: item.label || item.name || item // 确保有label
          }))
        } else {
          titleOptions.value = [] // 确保是数组
          console.warn('API返回的数据格式不符合预期:', res.data)
        }
      })
      .catch(err => {
        console.error('获取职称失败:', err)
        titleOptions.value = [] // 确保是数组
        ElMessage.error('获取职称选项失败')
      })
}


// const hospitalOptions = ref([])
// const getHospitalOptions = () => {
//   axios.get("/doctor/getHospital").then(res=>{
//     console.log(res.data.obj)
//     hospitalOptions.value = res.data.obj.map(item => ({
//       value: item.id || item.value || item,    // 使用 id 作为 value
//       label: item.name || item.label || item,   // 使用 name 作为 label
//     }))
//   })
// }

// // 科室选项 (模拟数据)
// const departmentOptions = ref([])
// const getDepartmentOptions = () => {
//   axios.get("/department/getAllLevel2Departments").then(res=>{
//     departmentOptions.value = res.data.obj.map(item=>({
//       value: item.id || item.value || item,
//       label:  item.name || item.label || item
//     }))
//   })
// }
// 头像上传处理
const uploading = ref(false); // 添加上传状态
const handleAvatarChange = async (file) => {
  // 显示加载状态
  uploading.value = true;

  try {
    // 创建 FormData 对象
    const formData = new FormData();
    formData.append('file', file.raw);  // 使用 file.raw 获取原始文件对象

    // 调用上传接口
    const response = await axios.post('/api/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (response.status === 200) {
      // 获取返回的图片 URL 并设置到表单
      form.value.avatar = response.data;
      ElMessage.success('头像上传成功');
    } else {
      ElMessage.error('头像上传失败');
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error(`头像上传失败: ${error.message}`);
  } finally {
    uploading.value = false;
  }
}

// 提交表单
const handleSubmit = () => {
axios.post('/doctor/addDoctor',form.value).then(res=>{
  if(res.data.code===200){
    ElMessage.success('提交成功')
    router.push('/doctor')
  }
  ElMessage.error('提交失败')
})
}

// 取消
const handleCancel = () => {
  router.push('/doctor')
  ElMessage.info('已取消')
}
onMounted(() => {
  getTitleOptions();
  // getHospitalOptions();
  // getDepartmentOptions();
})
</script>

<style scoped>
.doctor-form-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.form-card {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  text-align: center;
  color: #303133;
}

.avatar-uploader {
  display: flex;
  align-items: center;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  background-color: #f5f7fa;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  margin-right: 20px;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 6px;
  object-fit: cover;
  margin-right: 20px;
}

.upload-tip {
  display: flex;
  flex-direction: column;
}

.tip-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.consultation-fee {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.phone-consultation {
  margin-left: 20px;
}

:deep(.el-input-number) {
  width: 150px;
}

:deep(.el-textarea) {
  width: 100%;
}
/* 添加上传状态提示样式 */
.uploading-text {
  color: #409EFF;
  font-size: 12px;
  margin-left: 10px;
}
</style>